<?php

/**
 * 
 * @project     : innoTweets 1.0
 * @author      : Dino (DBK)
 * 
 * @package     : Sign In
 * @description : User sign in & API authorization
 * 
 */
if (!defined('BASEPATH')) {
  exit('No direct script access allowed');
}

class Signin extends MY_Controller {

  private $api_token = NULL;
  private $api_app_data = NULL;

  public function __construct() {
    parent::__construct();

    // In case from api
    if ($this->is_post()) {
      $api_token = $this->sanitize($this->input->post('api_token', TRUE));
    } else {
      $api_token = $this->sanitize($this->input->get('api_token'));
    }

    // Settin API data
    if (!empty($api_token)) {
      $validate_app = @$this->validate_app($this->crypt->decrypt($api_token));
      if (!empty($validate_app)) {
        $this->api_token = $api_token;
        $this->api_app_data = $validate_app;
      }
    }

    // In normal case
    $signuser = $this->user_session->signuser();
    if ($signuser) {
      redirect('timeline');
      return;
    }
  }

  public function index() {

    // Init
    $signin_status = NULL;
    $username = $this->sanitize($this->input->get('username', TRUE));
    $redirect_url = $this->input->get('redirect_url', TRUE);

    // Checking request type
    if ($this->is_post()) {

      $signin_status = 2;

      // Getting inputs
      $username = $this->sanitize($this->input->post('username', TRUE));
      $password = $this->input->post('password', TRUE);

      // Get from hidden inputs
      $redirect_url = $this->input->post('redirect_url', TRUE);

      // Checking inputs
      if (!empty($username) && !empty($password)) {

        // Doing signin
        $signin = $this->user_session->signin($username, md5($password));

        // Checking sigin
        if (!empty($signin)) {

          // Setting current user
          $this->current_user = $this->user_session->signuser();

          // Checking API Login or Normal Login
          if (!empty($this->api_app_data)) {

            // Autorizing app for the user
            $this->api_model->authorize_app($this->api_app_data['app_id'], $this->current_user['user_id']);

            // Loging api authorization
            $log_msg = $username . ' authorize for "' . $this->api_app_data['app_name'] . '" from ' . $this->input->ip_address() . ' on ' . $this->agent->platform() . ' ' . $this->agent->browser() . ' ' . $this->agent->version();
            system_log('api_apps', $log_msg);

            // Redirect to set api auth
            redirect('api/set_auth?api_token=' . $this->api_token);
            return;
          } else {

            // Log login
            $log_msg = $username . ' from ' . $this->input->ip_address() . ' on ' . $this->agent->platform() . ' ' . $this->agent->browser() . ' ' . $this->agent->version();
            system_log('signin', $log_msg);

            // redirecting to settings page if profile is not complete
            if ($this->current_user['user_birthday_date'] == '0000-00-00 00:00:00' || $this->current_user['user_join_date'] == '0000-00-00 00:00:00' || $this->current_user['user_position'] == '' || $this->current_user['user_skills'] == '' || $this->current_user['user_experience'] == '' || $this->current_user['user_place'] == '') {
              redirect('settings/profile');
              return;
            }

            // Update 1 activity point for daily login
            if (date('dmy') != date('dmy', strtotime($this->current_user['user_online_date']))) {
              $user_update_data = array();
              $user_update_data['user_likes_level'] = (int) $this->current_user['user_likes_level'] + 1;
              $this->user_model->update_profile($this->current_user['user_id'], $user_update_data);
            }

            // Redirect if redirect url is set
            if (!empty($redirect_url)) {
              redirect($redirect_url);
            }

            // Redirect to home page
            redirect('timeline');
            return;
          }
        }
      }

      // Setting signing error status
      $this->session->set_flashdata('signin_status', $signin_status);

      $apnd_username = NULL;
      if (!empty($username)) {
        $apnd_username = '&username=' . $username;
      }

      // Redirect to self. if error occured
      if (!empty($this->api_token)) {
        redirect('signin?api_token=' . $this->api_token . $apnd_username);
      } else {
        if ($redirect_url) {
          redirect('signin?redirect_url=' . $redirect_url . $apnd_username);
        } else {
          redirect('signin?login_error=true' . $apnd_username);
        }
      }
      return;
    }

    // Loading view
    $view_data = array();
    $view_data['username'] = $username;
    $view_data['redirect_url'] = $redirect_url;
    $view_data['api_token'] = $this->api_token;
    $view_data['app_data'] = $this->api_app_data;
    $this->load_view('signin', $view_data);
    return;
  }

  /**
   * Validate an api app from the provided api token
   * 
   */
  private function validate_app($app_token = NULL) {

    // Checking api token
    if (!empty($app_token)) {

      // Decoding data from token
      $req_data = @json_decode(base64_decode($app_token));

      // Checking decoded data
      if (!empty($req_data)) {

        // Evaluating decoded data
        if (isset($req_data->app_token) && !empty($req_data->app_token) && isset($req_data->app_callback) && !empty($req_data->app_callback)) {

          // Getting app details
          $get_app_by_token = $this->api_model->get_app_by_token($req_data->app_token);

          // Checking app details
          if ($get_app_by_token['status'] == 1 && !empty($get_app_by_token['result'])) {

            // Setting app data
            $app_data = array();
            $app_data = $get_app_by_token['result'];
            $app_data['app_callback'] = $req_data->app_callback;
            if (isset($req_data->user_id)) {
              $app_data['current_user_id'] = $req_data->user_id;
            }

            // Returning app data
            return $app_data;
          }
        }
      }
    }
    return NULL;
  }

}

?>